package org.dmikis.jmmengine.controllers;

import org.dmikis.jmmengine.models.Model;
import org.dmikis.jmmengine.viewes.*;

/**
 * @author dmikis
 *
 */
public class ModelComputer implements Runnable {
    
    public ModelComputer(Model m) {
	this.model = m;
    }
    
    public void start() throws IllegalThreadStateException {
	this.computingThread = new Thread(this, "Model Computing Thread");
	this.statusThread = new Thread(new Runnable() {

	    @Override
	    public void run() {
		try {
		while (statusThreadRunningFlag) {
		    statusBar.setStatus("Running: " + model.getStatus() + "%");
		    Thread.sleep(200);
		}
		}
		catch (Exception e) {}
	    }
	}, "Status Refresh Thread");
	this.statusThreadRunningFlag = true;
	this.computingThread.start();
	this.statusThread.start();
	this.statusBar.setStatus("Running...");
    }
    
    public void stop() {
	this.statusThreadRunningFlag = false;
	// TODO: implement case doesn't use stop() method.
	if (this.computingThread.isAlive()) {
	    this.computingThread.stop();
	    this.statusBar.setStatus("Stopped! Image may be corrupted!");
	}
	else {
	    this.statusBar.setStatus("Computing isn't running.");
	}
    }

    @Override
    public void run() {
	this.model.compute();
	this.statusThreadRunningFlag = false;
	this.statusBar.setStatus("Complete.");
    }
    
    /**
     * Associate model to the given status bar to show model status.
     *  
     * @param bar status bar
     */
    public StatusBar setStatusBar(StatusBar bar) {
	this.statusBar = bar;
	return bar;
    }

    private volatile Model model;
    private StatusBar statusBar;
    private Thread computingThread;
    private Thread statusThread;
    private volatile boolean statusThreadRunningFlag = true;
}
